/* eslint-disable no-redeclare */
/* eslint-disable no-undef */
import store from '../store/index'

var colorsRender = [
    '#989797',
    '#E1E1E1',
    '#F9DCCC',
    '#E29071',
    '#A02B30'
]

export default {
    // 初始化地图方法
    mapInit(opt) {
        let map = new AMap.Map("container", {
            viewMode: '3D', 
            mapStyle: "amap://styles/dark",
            zoom: opt.zoom,
            center: opt.center,
            layers: []
        })
        // 实例化覆盖物群组
        let overlayGroup = new AMap.OverlayGroup()

        // 添加到地图
        map.add(overlayGroup)

        // 返回地图、覆盖物群组
        return { map, overlayGroup }
    },

    // ***覆盖物操作***
    // 添加覆盖物
    overlaysAddItem(overlayGroup, item) {
        return Array.isArray(item) && overlayGroup.addOverlays(item) || overlayGroup.addOverlay(item)
    },
    // 删除覆盖物
    overlaysRemoveItem(overlayGroup, item) {
        return Array.isArray(item) && overlayGroup.removeOverlays(item) || overlayGroup.removeOverlay(item)
    },
    // 获取覆盖物
    overlaysGetItem(overlayGroup, item) {
        // 如果有item，返回Boolean；如果没有，返回所有覆盖物Array
        return item && overlayGroup.hasOverlay(item) || overlayGroup.getOverlays()
    },

    //设置图层级别可见，在map的zoomend事件中使用
    setZoomsVisable(map, Layer, level1, level2) {
        var zoom = map.getZoom();

        if (zoom > level1 && zoom < level2) {
            Layer.show();
        } else {
            Layer.hide();
        }
    },

    // 覆盖物操作员
    overlayOperator(map, overlayGroup, renderType, renderData) {
        // 参数：渲染类型、渲染数据
        switch (renderType) {
            case '边界':
                var boundary = this.boundaryGenerator(renderData)
                this.overlaysAddItem(overlayGroup, boundary)
                return boundary

            case '填色':
                var polygon = this.polygonGenerator(renderData, 0, 10)
                this.overlaysAddItem(overlayGroup, polygon)
                return polygon

            case '散点':
                var scatter = this.scatterGenerator(renderData)
                this.overlaysAddItem(overlayGroup, scatter)
                return scatter

            case '聚合':
                var join = this.joinGenerator(renderData, map)
                this.overlaysAddItem(overlayGroup, join)
                return join

            case '热力':
                var heat = this.heatGenerator(renderData, map)
                this.overlaysAddItem(overlayGroup, heat)
                return heat

            case 'OD': //有问题
                var od = this.odGenerator(renderData, map)
                this.overlaysAddItem(overlayGroup, od)
                return od

            case '轨迹': //有问题
                var track = this.trackGenerator(renderData, map)
                this.overlaysAddItem(overlayGroup, track)
                return track
        }
    },

    // 覆盖物生成器方法
    // 边界（可用）
    boundaryGenerator(data) {
        return new AMap.GeoJSON({
            geoJSON: data,
            getPolygon: (data, lnglats) => {
                return new AMap.Polygon({
                    path: lnglats,
                    strokeColor: '#fff',
                    strokeOpacity: 0.5,
                    fillColor: '#fff',
                    fillOpacity: 0.2
                })
            }
        })
    },

    // 填色（可用）
    polygonGenerator(data){  
        let colorValue = data.classBreaks
        let geojson = new AMap.GeoJSON({
            geoJSON: data,
            getPolygon: function(data, lnglats) {
                let color2,
                    countC = data.properties._parentProperities ?
                    data.properties._parentProperities.count :
                    data.properties.count
                for (let i = 0; i < colorValue.length; i++) {
                    if (countC >= colorValue[i]) {
                        color2 = colorsRender[i]
                    }
                }
                return new AMap.Polygon({
                    path: lnglats,
                    strokeColor: "white",
                    strokeOpacity: 0.2,
                    fillOpacity: 0.6,
                    fillColor: color2
                });
            }
        });

        // 填色图点击
        geojson.on("click", function(e) {
            let obj = e.target,
                prop = obj.getExtData(),
                xzcode = prop._geoJsonProperties._parentProperities ?
                prop._geoJsonProperties._parentProperities.xz_code :
                prop._geoJsonProperties.xz_code,
                tazcode = prop._geoJsonProperties._parentProperities ?
                prop._geoJsonProperties._parentProperities.taz_code :
                prop._geoJsonProperties.taz_code

            console.log(xzcode)
            console.log(tazcode)
                // 点击于后台交互方式待确认
        });
        return geojson;
    },

    // 散点（可用）
    scatterGenerator(data) {
        var markers = []
        for (var i = 0; i < data.length; i += 1) {
            var center = new AMap.LngLat(data[i].lng, data[i].lat);
            var circleMarker = new AMap.CircleMarker({
                center: center,
                radius: 4, //3D视图下，CircleMarker半径不要超过64px
                strokeColor: 'white',
                strokeWeight: 0.5,
                strokeOpacity: 0.5,
                fillColor: '#1abc9c',
                fillOpacity: 0.5,
                zIndex: 10,
                bubble: true,
                cursor: 'pointer',
                clickable: true
            })
            markers.push(circleMarker)
        }
        return markers;
    },

    // 聚合点（可用）
    joinGenerator(data, map){
        let markers = data.map((item, i)=>{
            const {lng, lat, info1, info2, qx_name, xz_name, count} = item
            let mExtData = {
                'id': i,
                'info1': qx_name || info1,
                'info2': info2 || '',
                'info3': info2 ? '' : xz_name,
                'count': count
            }
            let mk = new AMap.Marker({
                position: new AMap.LngLat(lng, lat),
                extData: mExtData,
                content: '<div style="background-color: hsla(180, 100%, 50%, 0.7); height: 24px; width: 24px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 1px;"></div>',
                offset: new AMap.Pixel(-15, -15)
            })
            mk.on('click', function(e) {
                let extdata = e.target.getExtData()
                let info = [(extdata.info1 + "<br>" + extdata.info2 + extdata.info3 + "：" + extdata.count)]
                let infoWindow = new AMap.InfoWindow({
                    isCustom: true,
                    content: info.join("<br/>")
                })
                infoWindow.open(map, e.lnglat);
            })
            return mk
        })
        return new AMap.MarkerClusterer(map, markers, {
            gridSize: 80,
        })
    },

    // 热力（可用）
    heatGenerator(data, map){
        let heatmap,
            ptArr = data.map(item=>({lng:item.lng, lat:item.lat}))
        map.plugin(["AMap.Heatmap"], function() {
            heatmap = new AMap.Heatmap(map, {
                radius: 15, //给定半径
                opacity: [0, 0.8]
            });
            heatmap.setDataSet({
                data: ptArr,
                max: 1
            });
        });
        return heatmap;
    },

    // OD
    odGenerator(data, map) {
        var object3Dlayer = new AMap.Object3DLayer({ zIndex: 10 });

        map.add(object3Dlayer);
    
        var Line3D = new AMap.Object3D.Line();
        Line3D.transparent = true;
    
        var geometry = Line3D.geometry;
    
        // for (var i = 0; i < data.length; i++) {
        data.map(item=>{
            var lnglat1 = new AMap.LngLat(item.o_lng, item.o_lat)
            var v0xy = map.lngLatToGeodeticCoord(lnglat1);
            geometry.vertices.push(v0xy.x, v0xy.y, 0);
            geometry.vertexColors.push(0, 0.4, 1, 0.3);

            var lnglat2 = new AMap.LngLat(item.d_lng, item.d_lat)
            var v1xy = map.lngLatToGeodeticCoord(lnglat2);
            geometry.vertices.push(v1xy.x, v1xy.y, 0);
            geometry.vertexColors.push(0, 0.4, 1, 0.3);
        })
            // 线段
            // var od = data[i].line;
            // o
            // var origin = od[0].split(',');
            // let origin = map.lngLatToGeodeticCoord([origin[0], origin[1]]);
            // let origin = map.lngLatToGeodeticCoord([data.o_lng, data.o_lat]);
            // console.log(data.o_lng)
            // geometry.vertices.push(data.o_lng, data.o_lat, 0);
            // geometry.vertexColors.push(0, 0.4, 1, 0.3);
            // d
            // var des = od[1].split(',');
            // let des = map.lngLatToGeodeticCoord([des[0], des[1]]);
            // let des = map.lngLatToGeodeticCoord([data.d_lng, data.d_lat]);
            // geometry.vertices.push(data.d_lng, data.d_lat, 0);
            // geometry.vertexColors.push(0, 0.4, 1, 0.3);
        // }
    
        object3Dlayer.add(Line3D)
        return object3Dlayer
    },


    // --------------------------------------------------------------------------------------



    // 影像栅格
    addRaster(map, url, bounds) {
        // if (this.imageLayer) {
        //     map.remove(this.imageLayer);
        // }
        // if (this.polygonColors) {
        //     map.remove(this.polygonColors);
        // }
        this.imageLayer = new AMap.ImageLayer({
            url: url,
            bounds: new AMap.Bounds(
                bounds[0], bounds[1]
                // [116.514615, 39.591903], [116.947859, 40.030671]
            ),
            zooms: [3, 18]
        });
        this.imageLayer.setMap(map)
        return this.imageLayer
            // return this.imageLayer
    },
    //海量点添加方法
    addMassMarks(map, geoJSON) {
        var style = [{
            url: 'https://a.amap.com/jsapi_demos/static/images/mass0.png',
            // eslint-disable-next-line no-undef
            anchor: new AMap.Pixel(6, 6),
            size: new AMap.Size(11, 11)
        }, {
            url: 'https://a.amap.com/jsapi_demos/static/images/mass1.png',
            anchor: new AMap.Pixel(4, 4),
            size: new AMap.Size(7, 7)
        }, {
            url: 'https://a.amap.com/jsapi_demos/static/images/mass2.png',
            anchor: new AMap.Pixel(3, 3),
            size: new AMap.Size(5, 5)
        }];

        var citys = [];
        for (var i = 0; i < geoJSON.length; i++) {
            var lng = flag == 0 ? geoJSON[i].o_lng : geoJSON[i].d_lng;
            var lat = flag == 0 ? geoJSON[i].o_lat : geoJSON[i].d_lat;
            citys.push({
                lnglat: [lng, lat],
                name: 'test',
                style: 2
            })
        }
        var mass = new AMap.MassMarks(citys, {
            opacity: 0.8,
            zIndex: 111,
            cursor: 'pointer',
            style: style
        });
        mass.setMap(map);
    }
}